package com.yingxue.lesson.service.impl;

import com.yingxue.lesson.entity.SysUserRole;
import com.yingxue.lesson.exception.BusinessException;
import com.yingxue.lesson.exception.code.BaseResponseCode;
import com.yingxue.lesson.mapper.SysUserRoleMapper;
import com.yingxue.lesson.service.UserRoleService;
import com.yingxue.lesson.vo.req.userVo.UserOwnRoleReqVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class UserRoleServiceImpl implements UserRoleService {

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Override
    public List<String> getRoleIdsByUserId(String userId) {
        return userRoleMapper.getRoleIdsByUserId(userId);
    }

    /**
     * 添加用户角色
     */
    @Override
    public void addUserRoleInfo(UserOwnRoleReqVO vo) {
        //1.删除他们关联的数据

        userRoleMapper.removeRoleByUserId(vo.getUserId());
        if (vo.getRoleIds() == null || vo.getRoleIds().isEmpty()){
            return;
        }
        //2.添加角色
        List<SysUserRole> list=new ArrayList<>();
        //遍历角色id
        for (String roleId: vo.getRoleIds()) {
            SysUserRole sysUserRole=new SysUserRole();
            sysUserRole.setId(UUID.randomUUID().toString());
            sysUserRole.setCreateTime(new Date());
            sysUserRole.setUserId(vo.getUserId());
            sysUserRole.setRoleId(roleId);
            list.add(sysUserRole);
        }
        int count = userRoleMapper.batchInsertUserRole(list);
        if (count == 0){
            throw new BusinessException(BaseResponseCode.OPERATION_ERROR);
        }
    }


    /**
     * 根据角色id集合获取所有关联用户di集合
     */
    @Override
    public List<String> getUserIdsByRoleIds(List<String> roleIds) {
        return userRoleMapper.getUserIdsByRoleIds(roleIds);
    }

    /**
     * 通过角色id 获取跟该角色关联的用户id
     */
    @Override
    public List<String> getUserIdsByRoleId(String roleId) {
        return userRoleMapper.getUserIdsByRoleId(roleId);
    }

    /**
     * 通过角色id删除用户角色关联数据
     */
    @Override
    public int removeByRoleId(String roleId) {
        return userRoleMapper.removeByRoleId(roleId);
    }
}
